﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 测试工具
{
    public partial class UserControl2 : UserControl
    {
        private SerialPort uart = new SerialPort();
        public List<byte> serialReciveBytes = new List<byte>();
        public string serialReciveData = "";
        private Thread uartProcess = null;

        bool test_end = false;
        public UserControl2()
        {
            InitializeComponent();
        }

        private void UserControl2_SizeChanged(object sender, EventArgs e)
        {
            start_button.Location = new System.Drawing.Point(this.Size.Width - 75, this.Size.Height - 25);

            comboBoxSerialBox.Location = new System.Drawing.Point(2, this.Size.Height - 25);
            comboBoxSerialBox.Size = new Size(this.Size.Width - 85, 20);

            Log_textBox.Size = new Size(this.Size.Width - 10, this.Size.Height - 30);
        }


        public void UpdateSerial()
        {
            string currentText = comboBoxSerialBox.Text;
            comboBoxSerialBox.Items.Clear();    //清空下拉框
            comboBoxSerialBox.Items.Add("关闭");  //添加第一个选项
            string[] serial = SerialPort.GetPortNames(); //获取系统串口 
            foreach (string s in serial)    //将串口号添加到下拉框中
            {
                comboBoxSerialBox.Items.Add(s);
            }
            if (null == currentText || currentText.Equals(""))
            {
                comboBoxSerialBox.SelectedIndex = 0;
            }
            else
            {
                comboBoxSerialBox.Text = currentText;
            }
        }

        private void UartReadData(object sender, SerialDataReceivedEventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;//添加这一句即可在线程中调用其他线程创建的控件
            while (true)
            {
                if (!uart.IsOpen)
                {
                    return;
                }
                int len = uart.BytesToRead;
                if (len == 0)
                {
                    break;
                }
                byte[] readBytes = new byte[len];
                try
                {
                    if (uart.IsOpen)
                    {
                        uart.Read(readBytes, 0, len);
                    }
                }
                catch
                {
                    Console.WriteLine("数据接收异常");
                    continue;
                }
                serialReciveBytes.AddRange(readBytes);
                string tmpRecive = System.Text.Encoding.UTF8.GetString(readBytes);
                serialReciveData = tmpRecive;  //保存为string格式
                Log_textBox.AppendText(serialReciveData);
            }
        }

        public void start_button_Click(object sender, EventArgs e)
        {
            if (comboBoxSerialBox.Text.Equals("关闭"))
            {
                Log_textBox.AppendText("未选择串口\r\n");
                return;
            }

            if (start_button.Text.Equals("开始"))
            {
                Log_textBox.Text = "";
                if (comboBoxSerialBox.Text.Length == 0)
                {
                    MessageBox.Show("请选择串口", "错误提示");
                    return;
                }
                uart.BaudRate = 115200;
                uart.Parity = System.IO.Ports.Parity.None;
                uart.StopBits = System.IO.Ports.StopBits.One;
                uart.DataBits = 8;
                uart.PortName = comboBoxSerialBox.Text;
                uart.DataReceived += new SerialDataReceivedEventHandler(UartReadData);
                try
                {
                    uart.Open();
                }
                catch
                {
                    MessageBox.Show("打开串口失败", "错误提示");
                    return;
                }
                start_button.Text = "停止";
                Log_textBox.AppendText("启动测试...\r\n");
                comboBoxSerialBox.Enabled = false;

                uartProcess = new Thread(UartProcess);
                uartProcess.IsBackground = true;
                uartProcess.Start();
            }
            else
            {
                uart.Close();
                start_button.Text = "开始";
                Log_textBox.AppendText("停止测试\r\n");
                comboBoxSerialBox.Enabled = true;
                uartProcess.Abort();
            }
        }


        private void RST()
        {
            uart.DtrEnable = false;
            uart.RtsEnable = true;
            System.Threading.Thread.Sleep(100);
            uart.RtsEnable = false;
        }

        public void CleanRecive()
        {
            serialReciveData = "";
            serialReciveBytes.Clear();
        }

        public string CheckResponse(string cmd, string response)
        {
            CleanRecive();  //清空数据
            try
            {
                uart.Write(cmd);    //发送AT指令
            }
            catch
            { 
                
            }

            Thread.Sleep(500);
            while (true)
            {
                if (serialReciveData.Contains(response))
                {
                    break;
                }

                try
                {
                    uart.Write(cmd);
                }
                catch
                {
                    continue;
                }

                Thread.Sleep(500);
            }
            return "";
        }

        private void UartProcess()
        {
            Control.CheckForIllegalCrossThreadCalls = false;//添加这一句即可在线程中调用其他线程创建的控件
            while (true)
            {
                //Log_textBox.AppendText("等待复位\r\n");
                RST();
                Thread.Sleep(1000);
                UserControl1.test_num++;
                UserControl1.userControl13.test_num_label.Text = "测试次数:" + UserControl1.test_num;
                //Log_textBox.AppendText("\r\n复位成功\r\n");
                string err = CheckResponse("AT+BLEINIT=2\r\n", "OK\r\n");
                if (err.Equals("err"))
                {
                    UserControl1.test_ng_num++;
                    UserControl1.userControl13.test_ng_label.Text = "NG次数:" + UserControl1.test_ng_num;
                    Log_textBox.AppendText("\r\n测试失败！！！！！！！！！！！！！！！！\r\n");
                }
                else
                {
                    Log_textBox.AppendText("测试通过\r\n");
                }
                Thread.Sleep(1000);
            }
        }
    }
}
